﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Admin.Models;

namespace OT.Areas.Admin.Controllers
{
    public class ChangePassController : Controller
    {
        #region Declaration
        readonly OTEntitiesme OTDb = new OTEntitiesme();
        #endregion

        #region Index
        public ActionResult Index()
        {
            int UserID = 0;
            if (Request.Cookies["UserSettings"] != null)
            {
                if (Request.Cookies["UserSettings"]["AdminID"] != null)
                {
                    UserID = Convert.ToInt16(Request.Cookies["UserSettings"]["AdminID"]);
                }
                else
                {
                    TempData["notice"] = "Time Out ,Please Login";
                    Response.Redirect("~/Home");
                }
            }
            ChangePass ChangePass = null;
            try
            {
                var User = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                if (User != null)
                {
                    ChangePass = new ChangePass();
                    ChangePass.Password = User.Password;  
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return View();
        }

        [HttpPost]
        public string Index(ChangePass change)
        {
            string result="NotValid";
            try
            {

                int UserID = Convert.ToInt16(Request.Cookies["UserSettings"]["AdminID"]); 
                 var User = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                    if (User != null)
                    {
                        if(User.Password==change.Password)
                        {
                            User.Password = change.NewPassword;
                            OTDb.SaveChanges();
                            TempData["notice"] = "Password Successfully Update";
                           result="Valid";
                        }
                        else
                        {
                            ModelState.AddModelError("", "Old password is incorrect!");
                        }
                    }
               
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion
    }
}
